import { useEffect, useState } from 'react'
import './citylist.scss'
import axios from 'axios'
import Headernav from '../../components/headerNav/Headernav'
type Props = {
    history: any,
    location: any
}

export default function Citylist(props: Props) {

    // console.log(props);
    

    let url = 'http://localhost:8080'

    useEffect(() => {
        getCitylist()
        document.querySelector('.citycontent')?.addEventListener('scroll',scrollHandle)
        return () => {
            document.querySelector('.citycontent')?.removeEventListener('scroll',scrollHandle);
        }
    }, [])




    let code = ['#', '热','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    let [newcode, setnewcode] = useState<string[]>([])
    let [citylist, setCitylist] = useState<any>([])

    let [currentIndex, setCurrentIndex] = useState<number>(0)


    // 获取城市列表并且进行处理
    const getCitylist = async () => {
        let {data:{body:data}} = await axios.get(url + '/area/city?level=1')
        let {data:{body:data2}} = await axios.get(url + '/area/hot')
        let key = []
        key.push({name:'当前定位',value:'#', clist:[JSON.parse(window.sessionStorage.getItem('currentCity') || JSON.stringify({label:"广州",value:"AREA|e4940177-c04c-383d",pinyin:"guangzhou", short:"gz"}))]})
        key.push({name:"热门城市",value:'热', clist:[...data2]})
        code.slice(2,).forEach((item:any) => {
            let clist:any = []
            data.forEach((subitem:any) => {
                if(subitem.short[0].toUpperCase() === item){
                    clist.push(subitem)
                }
            })
            if(clist.length){
                key.push({name:item,value:item, clist})
            }else{
                code = code.filter(i => i !== item)
            }
        })
        setnewcode(code)
        setCitylist(key)
    }


    // 点击右侧字母定位到指定位置
    const positionArea = (e:any) => {
        let key = e.target.innerText
        if(key.length <= 1){
            // console.log(key);
            let index = newcode.findIndex(item => item === key)
            setCurrentIndex(index)
            let currentDom = document.querySelectorAll('.cityitem')[index] as HTMLDivElement;
            currentDom.scrollIntoView({
                block:"start",
                // behavior:"smooth"
            })
        }
        
    }

    // 滚动事件
    const scrollHandle =  () => {
        let parentDom = document.querySelector('.citycontent') as HTMLDivElement;
        let scrollHeight = parentDom.scrollTop;
        let currentDom = document.querySelectorAll('.cityitem');
        let num = 0;
        currentDom.forEach((item, index) => {
            num += item.clientHeight;
            if(num < scrollHeight){
                setCurrentIndex(index + 1)
            }else if(!scrollHeight){
                setCurrentIndex(0)
            }
        })
    }

    // 点击选择城市
    const changeCity = async (e:any) => {
        let strobj = e.target.dataset.currentcity;
        if(!strobj) return
        
        // let obj = JSON.parse(strobj)
        // let data = await axios.get( url + '/area/map?id='+obj.value)
        // console.log(data);
        window.sessionStorage.setItem('currentCity', strobj)
        props.history.push({pathname:props.location.state.last})
    }

  return (
    <div className='citylist'>
        <Headernav title="城市列表"  backcolor="#f4f4f4" color="#000" />
        <div className='citycontent'>
            <div className='citylists' onClick={e=>changeCity(e)}>
                {
                    citylist.map((item:any, index:number) => (
                        <div key={index} className="cityitem">
                            <div className='itemtitle'>{item.name}</div>
                            {
                                item.clist.map((subitem:any) =>(
                                    <div key={subitem.value} className="city" data-currentcity={JSON.stringify(subitem)}>
                                        {subitem.label}
                                    </div>
                                ))
                            }
                        </div>
                    ))
                }
            </div>
        </div>
        <div className='rightBtn' onClick={(e)=>positionArea(e)}>
            {
                newcode.map((item:any, index:number) => (
                    <div key={index} className={index === currentIndex ? 'active' : ''}>{item}</div>
                ))
            }
        </div>
    </div>
  )
}